import { Wrapper } from "./styles";
import { Button, Modal, Form, Input, Typography } from "antd";
import { QuickMessageCard } from "./components/QuickMessageCard";
import { useViewModel } from "./model.view";
import type { QuickMessage } from "@common/models";

const FormItem = Form.Item<QuickMessage>;

export function XHSToolkits() {
  const {
    targetRecords,
    target,
    form,
    globalModel,

    onCreateClick,
    editorVisible,
    onSubmitClick,
    onCancelClick,
    onEditClick,
    onDeleteClick,
    onRecordSelect,
  } = useViewModel();
  return (
    <Wrapper className={"xhs-toolkits"}>
      <div className={"toolkits-controller"}>
        <div>话术库</div>
        <Button size={"small"} type={"primary"} onClick={onCreateClick}>
          添加新话术
        </Button>
      </div>
      <div className={"quick-message-list"}>
        {!!globalModel.quickMessageInput && (
          <div className={"filter-tip"}>
            筛选模式，按下 <Typography.Text keyboard={true}>/</Typography.Text>{" "}
            选择第一项，或者直接鼠标点击选择
          </div>
        )}
        {targetRecords.map((r) => (
          <div key={r.id}>
            <QuickMessageCard
              record={r}
              onDeleteClick={onDeleteClick}
              onEditClick={onEditClick}
              readonly={!!globalModel.quickMessageInput}
              onSelect={onRecordSelect(r)}
            />
          </div>
        ))}
      </div>

      <Modal
        title={target ? "修改话术" : "新增话术"}
        open={editorVisible}
        onOk={onSubmitClick}
        destroyOnClose={true}
        onCancel={onCancelClick}
        onClose={onCancelClick}
        width={400}
      >
        <Form autoComplete={"off"} form={form} labelCol={{ span: 4 }}>
          {target && (
            <FormItem label={"ID"} name={"id"}>
              <Input disabled={true} />
            </FormItem>
          )}

          <FormItem
            label={"标题"}
            name={"title"}
            rules={[{ required: true, message: "必填" }]}
          >
            <Input />
          </FormItem>

          <FormItem
            label={"缩写"}
            name={"shortcut"}
            required={true}
            rules={[
              {
                validator: async (_, val) => {
                  if (!val) {
                    throw new Error("必填");
                  } else if (!val.match(/^[a-zA-Z0-9]+$/)) {
                    throw new Error("只支持英文字母和数字");
                  }
                },
              },
            ]}
          >
            <Input />
          </FormItem>

          <FormItem
            label={"内容"}
            name={"content"}
            rules={[{ required: true, message: "必填" }]}
          >
            <Input.TextArea />
          </FormItem>
        </Form>
      </Modal>
    </Wrapper>
  );
}
